package org.zhb.sys.shiro.function.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.zhb.sys.shiro.function.repository.FunctionRepository;
import org.zhb.sys.shiro.function.service.FunctionService;

import org.zhb.sys.shiro.model.Function;

/**
 * Function服务实现。
 * 
 * @author zhb
 *
 */
@Service
public class FunctionServiceImpl implements FunctionService {
	@Autowired
	private FunctionRepository functionRepository;

	@Override
	public Function insert(Function function) {
		return functionRepository.saveAndFlush(function);
	}

	@Override
	public Function selectFunctionById(String id) {
		/**
		 * 注意:这里查询使用getOne和findOne的区别在于:
		 * getOne返回的是一个引用对象,返回与给定实体的引用标识符.是一个懒加载的对象 findOne则根据Id返回对象本身
		 */
		return functionRepository.findOne(id);
	}

	@Override
	public Function update(Function function) {
		return functionRepository.saveAndFlush(function);
	}

	@Override
	public void delete(String id) {
		functionRepository.delete(id);
	}

	@Override
	public void saveBatch(List<Function> functions) {
		functionRepository.save(functions);
	}

	@Override
	public Page<Function> selectModelByCondition(Function function, PageRequest pageRequest) {
		Specification<Function> specification = getWhereClause(function);
		Page<Function> functionList = functionRepository.findAll(specification, pageRequest);
		return functionList;
	}

	/**
	 * 条件拼接
	 * 
	 * @param function
	 * @return
	 */
	private Specification<Function> getWhereClause(Function function) {
		return new Specification<Function>() {
			@Override
			public Predicate toPredicate(Root<Function> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>();
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		};
	}

	@Override
	public Page<Function> selectModelByCondition(PageRequest pageRequest) {
		return functionRepository.findAll(pageRequest);
	}

	@Override
	public List<Function> selectAllFunction() {
		return functionRepository.findAll();
	}
}